﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace yeqw.FrameWork
{
    public class ResponseFilter : Stream
    {
        private Stream _StreamFilter;

        private ResponseFilter() { }

        public ResponseFilter(Stream stream)
        {
            _StreamFilter = stream;
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        public override void Flush()
        {
            _StreamFilter.Flush();
        }

        public override long Length
        {
            get
            {
                return _StreamFilter.Length;
            }
        }

        public override long Position
        {
            get
            {
                return _StreamFilter.Position;
            }
            set
            {
                _StreamFilter.Position = value;
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return _StreamFilter.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return _StreamFilter.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            _StreamFilter.SetLength(value);
        }
       
        public override void Write(byte[] buffer, int offset, int count)
        {
            string Html = Encoding.UTF8.GetString(buffer);
            Html = Regex.Replace(Html, @">\s+?<", "><");//去除Html中的空白字符.
            Html = Regex.Replace(Html, @"\r\n\s*", "");
            Html = Html.Replace("//<![CDATA[", "//<![CDATA[\r\n");
            Html = Regex.Replace(Html, "//]]>", "//]]>\r\n");
            buffer = Encoding.UTF8.GetBytes(Html);
            _StreamFilter.Write(buffer, offset, buffer.Length);
            _StreamFilter.Close();
        }
    }
}
